package com.lyy.photovoltaic.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lyy.photovoltaic.beans.*;
import com.lyy.photovoltaic.common.utils.DateUtil;
import com.lyy.photovoltaic.common.utils.MyRandom;
import com.lyy.photovoltaic.common.vo.ResultCode;
import com.lyy.photovoltaic.common.vo.ResultVO;
import com.lyy.photovoltaic.mapper.*;
import com.lyy.photovoltaic.service.OrdersDetailsService;
import com.lyy.photovoltaic.service.OrdersService;
import com.lyy.photovoltaic.service.UserEquipmentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    OrdersDetailsService ordersDetailsService;
    @Autowired
    OrdersDetailsMapper ordersDetailsMapper;
    @Autowired
    UsersInfoMapper usersInfoMapper;
    @Autowired
    UsersEquipmentsListsMapper usersEquipmentsListsMapper;
    @Autowired
    UserEquipmentsService userEquipmentsService;

    @Override
    public ResultVO addOrders(JSONObject jsonObject) {
//        System.out.println(jsonObject);
        Orders order = new Orders();
        String string = jsonObject.getJSONObject("data").getString("userId");
        String oId = System.currentTimeMillis() + string;
        order.setOrderId(oId);
        order.setOrderOwner(jsonObject.getJSONObject("data").getString("orderName"));
        order.setOrderPhone(jsonObject.getJSONObject("data").getString("phone"));
        order.setOrderAddress(jsonObject.getJSONObject("data").getString("address"));
        order.setOrderCreatetime(new Date());
        order.setOrderStatus(true);
        order.setOrderIsshowtouser(true);
        order.setOrderAmount(jsonObject.getJSONObject("data").getString("amount"));
        order.setUserId(jsonObject.getJSONObject("data").getString("userId"));
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("orderDetails");
//        System.out.println(jsonArray);
        /*  用StringJoiner作字符串拼接  */
        StringJoiner EId = new StringJoiner(",");    //分别为：分隔符、前缀、后缀，也可以只传第一个参数分隔符
        StringJoiner UCId = new StringJoiner(",");
        if (jsonArray != null && jsonArray.size() > 0) {
            OrdersDetails[] ordersDetails = new OrdersDetails[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jo = jsonArray.getJSONObject(i);
                String eId = jo.get("eId").toString();
                EId.add(eId);
                String uCId = System.currentTimeMillis() + MyRandom.getStringRandom() + eId;
                UCId.add(uCId);
                String eCount = jo.get("count").toString();
                String eRealPrice = jo.get("realPrice").toString();
                String eName = jo.get("name").toString();
                System.out.println(eName);
                BigDecimal eRealPrice1 = new BigDecimal(eRealPrice);
                String ePrice = jo.get("price").toString();
                BigDecimal ePrice1 = new BigDecimal(ePrice);
                ordersDetails[i] = new OrdersDetails();
                ordersDetails[i].setOrderDetailsId(uCId);
                ordersDetails[i].seteId(eId);
                ordersDetails[i].seteName(eName);
                ordersDetails[i].seteCount(Integer.valueOf(eCount));
                ordersDetails[i].seteRealprice(eRealPrice1);
                ordersDetails[i].setePrice(ePrice1);
//                System.out.println(i);
                ResultVO resultVO = ordersDetailsService.addOrdersDetails(ordersDetails[i]);
//                System.out.println("ordersDetails:"+ordersDetails[i]);
            }
        }
//        System.out.println("EId:"+EId);
        order.setOrderDetailsId(UCId.toString());
//        System.out.println("UCId:"+UCId);
//        System.out.println(order);
        int i = ordersMapper.insert(order);
        if (i > 0) {
            return new ResultVO(ResultCode.SUCCESS, "添加订单成功", order);
        }
        return new ResultVO(ResultCode.FAILED, "添加订单失败", null);
    }

    @Override
    public ResultVO findOrders(String uId) {
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", uId);
        criteria.andEqualTo("orderIsshowtouser", true);
        List<Orders> orders = ordersMapper.selectByExample(example);
        for (Orders order : orders) {
            System.out.println(order);
            String orderDetailsId = order.getOrderDetailsId();
            String[] stringArr = orderDetailsId.split(",");
            List<OrdersDetails> orderDetailsLists = ordersDetailsMapper.findOrderDetailsLists(stringArr);
            order.setOrderDetailsList(orderDetailsLists);
        }
        if (orders.size() > 0) {
            return new ResultVO(ResultCode.SUCCESS, "查询订单成功", orders);
        }
        return new ResultVO(ResultCode.FAILED, "查询历史订单失败", null);
    }

    @Override
    public ResultVO logicDeleteOrders(String orderId) {
//        System.out.println(orderId);
        Orders order = new Orders();
        order.setOrderIsshowtouser(false);
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        int i = ordersMapper.updateByExampleSelective(order, example);
        if (i > 0) {
            return new ResultVO(ResultCode.SUCCESS, "逻辑删除历史订单成功");
        }
        return new ResultVO(ResultCode.FAILED, "逻辑删除成功历史订单失败", null);
    }

    @Override
    public ResultVO unProcessOrders() {
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNull("staffId");
        criteria.andIsNull("orderDeliveryAddress");
//        criteria.andNotEqualTo("staffId", null);
//        criteria.andNotEqualTo("orderDeliveryAddress", null);
        List<Orders> orders = ordersMapper.selectByExample(example);
        for (Orders order : orders) {
//            System.out.println(order);
            String orderDetailsId = order.getOrderDetailsId();
//            System.out.println(orderDetailsId);
            String[] stringArr = orderDetailsId.split(",");
//            System.out.println(Arrays.toString(stringArr));
            List<OrdersDetails> orderDetailsLists = ordersDetailsMapper.findOrderDetailsLists(stringArr);
            order.setOrderDetailsList(orderDetailsLists);
//            System.out.println(orderDetailsLists);
//            System.out.println(orders);
//            orderDetailsLists.ge

        }
//        System.out.println("-------------");
//        System.out.println(orders);
        if (orders.size() > 0) {
            return new ResultVO(ResultCode.SUCCESS, "查看未处理订单成功", orders);
        }
        return new ResultVO(ResultCode.FAILED, "查看未处理订单失败", null);

    }

    @Override
    public ResultVO UpdateOrders(String orderId, JSONObject jsonObject) {
        Orders order = ordersMapper.selectByPrimaryKey(orderId);
//        System.out.println(jsonObject);
        order.setOrderDeliveryAddress(jsonObject.getString("orderDeliveryAddress"));
        order.setStaffId(jsonObject.getString("staffId"));
//        System.out.println(order);
        //通过用户Id查看用户个人设备列表Id
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", order.getUserId());
        UsersInfo usersInfo = usersInfoMapper.selectOneByExample(example);
        String uelId = usersInfo.getUelId();//得到个人设备列表Id
        UsersEquipmentsLists usersEquipmentsList = usersEquipmentsListsMapper.selectByPrimaryKey(uelId);
        //给用用户个人设备列表添加个人设备信息
        String orderDetailsId = order.getOrderDetailsId();
//            System.out.println(orderDetailsId);
        String[] stringArr = orderDetailsId.split(",");
//            System.out.println(Arrays.toString(stringArr));
        List<OrdersDetails> orderDetailsLists = ordersDetailsMapper.findOrderDetailsLists(stringArr);
//        System.out.println(orderDetailsLists);
        String UeId = orderDetailsLists.stream().map(r -> MyRandom.getStringRandom() + r.geteId() + ",").collect(Collectors.joining(""));
        //给用户设备列表添加用户个人设备id信息
        String ueId = usersEquipmentsList.getUeId();
        if (ueId == null) {
            ueId = "";
        }
        StringBuffer stringBuffer = new StringBuffer(ueId);
        stringBuffer.append(UeId);
        usersEquipmentsList.setUeId(String.valueOf(stringBuffer));
        int i = usersEquipmentsListsMapper.updateByPrimaryKeySelective(usersEquipmentsList);
//        System.out.println(usersEquipmentsList);
//        System.out.println("------------------------------");
//        System.out.println(usersEquipmentsList);
//        System.out.println("------------------------------");
        String eId = orderDetailsLists.stream().map(OrdersDetails::geteId).collect(Collectors.joining(","));
//        System.out.println(eId);
//        System.out.println(UeId);
        //将UeId和eId添加到用户设备表
        List<String> UeIdLists = Arrays.asList(UeId.split(","));
        List<String> eIdLists = Arrays.asList(eId.split(","));
//
//        System.out.println("UeIdList");
//        System.out.println(UeIdLists);
//        System.out.println("UeIdList");
//        usersEquipmentsMapper.insertList(UeIdList)
        List<UsersEquipments> usersEquipments = new ArrayList<>();
        for (String UeIdList : UeIdLists) {
            UsersEquipments usersEquipment = new UsersEquipments();
            usersEquipment.setUeId(UeIdList);
            usersEquipment.setEquipmentId(UeIdList.substring(6));
            usersEquipment.setPeCreatetime(new Date());
            usersEquipment.setPeStatus(false);
            usersEquipments.add(usersEquipment);
        }
//        System.out.println(usersEquipments);
        int i1 = userEquipmentsService.addUsersEquipments(usersEquipments);
//        System.out.println(i1);
        int ii = ordersMapper.updateByPrimaryKeySelective(order);
        if (ii > 0) {
            ResultVO resultVO = new ResultVO(ResultCode.SUCCESS, "修改未处理订单成功", order);
            return resultVO;
        }
        return new ResultVO(ResultCode.FAILED, "修改未处理订单失败", null);
    }

    @Override
    public ResultVO historicalOrders() {
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNotNull("staffId");
        criteria.andIsNotNull("orderDeliveryAddress");
        List<Orders> orders = ordersMapper.selectByExample(example);
        for (Orders order : orders) {
            String orderDetailsId = order.getOrderDetailsId();
            String[] stringArr = orderDetailsId.split(",");
            List<OrdersDetails> orderDetailsLists = ordersDetailsMapper.findOrderDetailsLists(stringArr);
            order.setOrderDetailsList(orderDetailsLists);


        }
        if (orders.size() > 0) {
            return new ResultVO(ResultCode.SUCCESS, "查询历史订单成功", orders);
        }
        return new ResultVO(ResultCode.FAILED, "查询历史订单失败", null);
    }

    @Override
    public ResultVO dailyOrders() {
        Example example = new Example(Orders.class);
        Example.Criteria criteria = example.createCriteria();
        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 23:59:59");
        criteria.andGreaterThan("orderCreatetime", start);
        criteria.andLessThanOrEqualTo("orderCreatetime", end);
        List<Orders> orders = ordersMapper.selectByExample(example);
        for (Orders order : orders) {
            String orderDetailsId = order.getOrderDetailsId();
            String[] stringArr = orderDetailsId.split(",");
            List<OrdersDetails> orderDetailsLists = ordersDetailsMapper.findOrderDetailsLists(stringArr);
            order.setOrderDetailsList(orderDetailsLists);
        }
        if (orders.size() > 0) {
            return new ResultVO(ResultCode.SUCCESS, "查询当日订单成功", orders);
        }
        return new ResultVO(ResultCode.FAILED, "查询当日订单失败", null);
    }
}
